import React from 'react';
import styles from './index.less';
import { Button, DatePicker, Select, Space } from 'antd';
import moment from 'moment';

import { TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';
import { useStaticState, useTRState } from '#/utils/trHooks';
import { postQueryFilterNodeList } from '../../service';

const getDateRange = () => {
  return [moment().add(-7, 'day'), moment().add(-1, 'day')];
};

const Header = (props) => {
  const { power, buttonPermissions } = props;
  const _st = useStaticState({
    beginDate: '', // 开始日期
    endDate: '', // 结束日期
    marketId: '', // 交易中心编码
    provinceId: '', // 省份ID
    nodeIdList: [], // 节点ID
    marketName: '', // 展示使用: 交易中心名称
    nodeName: '全部节点', // 展示使用: 节点名称
  });
  const [state, setState] = useTRState({
    canExport: buttonPermissions.some((x) => x.menuCode === 'BlockPriceDiffPearsonButtonWeb'),
    // 表单
    marketItem: power[0], // 交易中心信息
    dates: getDateRange(), // 时间范围
    nodeItem: { label: '全部节点', value: 'all' }, // 节点信息
    // 节点选项
    nodeLoading: true,
    nodeList: [],
    nodeOptions: [{ label: '全部节点', value: 'all' }], // 节点列表(添加全部选项)
  });

  React.useEffect(() => {
    fetchNodes(power[0], 'isFirst');
  }, []);

  const fetchNodes = async (item, type) => {
    // 获取节点选项
    setState({ nodeLoading: true });
    const params = {
      marketId: item.value,
      provinceId: item.provinceId,
    };
    const nodeList = (await postQueryFilterNodeList(params))?.data || [];
    const nodeOptions = [
      { label: '全部节点', value: 'all' },
      ...nodeList.map((n) => ({
        label: n.nodeNameAlias, // 节点名称（分组）
        options: n.stationList.map((s) => ({
          label: s.stationName, // 交易单元名称
          value: s.stationId, // 交易单元ID
          nodeId: n.nodeId, // 节点ID
        })),
      })),
    ];
    state.nodeItem = { label: '全部节点', value: 'all' };
    state.nodeList = nodeList;
    state.nodeOptions = nodeOptions;
    setState({
      nodeItem: state.nodeItem,
      nodeList: state.nodeList,
      nodeOptions: state.nodeOptions,
      nodeLoading: false,
    });
    if (type === 'isFirst') {
      _onFinish(type);
    }
  };

  const _onFinish = (type) => {
    // 查询
    _st.beginDate = state.dates[0].format('YYYY-MM-DD');
    _st.endDate = state.dates[1].format('YYYY-MM-DD');
    _st.marketId = state.marketItem.value;
    _st.provinceId = state.marketItem.provinceId;
    _st.nodeIdList =
      state.nodeItem.value === 'all'
        ? state.nodeList.map((x) => x.nodeId)
        : [state.nodeItem.nodeId];
    _st.marketName = state.marketItem.label;
    _st.nodeName = state.nodeItem.label;
    props.onSearch?.(_st, type);
  };

  const _onReset = () => {
    // 重置
    state.marketItem = power[0];
    state.dates = getDateRange();
    state.nodeItem = { label: '全部节点', value: 'all' };
    setState({
      marketItem: state.marketItem,
      dates: state.dates,
      nodeItem: state.nodeItem,
    });
    // _onFinish();
  };

  const _onExport = () => {
    // 导出
    if (!state.canExport) return TRMessage.info('请联系管理员获取相关权限');
    props.handleExportFile?.();
  };

  return (
    <div className={styles.head}>
      <Space size={16} wrap>
        <Select
          value={state.marketItem.value}
          style={{ width: 200 }}
          options={power}
          optionFilterProp="label"
          showArrow
          showSearch
          onChange={(v, marketItem) => {
            setState({ marketItem });
            fetchNodes(marketItem);
          }}
        />
        <DatePicker.RangePicker
          value={state.dates}
          style={{ width: 216 }}
          separator="-"
          format="YYYYMMDD"
          allowClear={false}
          onChange={(dates) => setState({ dates })}
        />
        <Select
          style={{ width: 200 }}
          value={state.nodeItem.value}
          loading={state.nodeLoading}
          options={state.nodeOptions}
          optionFilterProp="label"
          showArrow
          showSearch
          onChange={(v, nodeItem) => setState({ nodeItem })}
        />
        <Space size={16}>
          <Button
            style={{ width: 98, height: 32 }}
            type="primary"
            disabled={state.nodeLoading}
            onClick={_onFinish}
          >
            查询
          </Button>
          <Button
            style={{ width: 98, height: 32 }}
            disabled={state.nodeLoading}
            ghost
            onClick={_onReset}
          >
            重置
          </Button>
        </Space>
      </Space>
      <Space size={16} wrap>
        <Button
          style={{ padding: 0 }}
          disabled={state.nodeLoading}
          type="link"
          icon={<UploadOutlined />}
          onClick={_onExport}
        >
          导出
        </Button>
      </Space>
    </div>
  );
};

export default Header;
